
import { TIP_INFO } from "../proto/ELProtocol";
// import Crypt = require("../utils/Crypt.js");
import { NotificationCenter } from "./NotificationCenter";

import xxtea = require("../utils/xxtea.js");
import md5 = require("../utils/Md5.js");

export const WX_READY = false;
export const gameVersion = "1.0.0";
export const cryptKey = "5XFn%jee0J*UuElu";
// export const httpUrl = "http://192.168.3.88:8080";
export const httpUrl = "http://192.168.3.15:8080";
// export const httpUrl = "https://yx.bigboluo.cn:8080";

export const loginUrl = httpUrl+"/login";
export const synInfoUrl = httpUrl+"/synInfo";
export const gunBuyUrl = httpUrl+"/gunBuy";
export const gunSellUrl = httpUrl+"/gunSell";
export const gunCompositeUrl = httpUrl+"/gunComposite";
export const gunChangePosUrl = httpUrl+"/gunChangePos";
export const changeWeaponUrl = httpUrl+"/gunFightChange";
export const compGoldUrl = httpUrl+"/gunCompositeCL";
export const listTaskUrl = httpUrl+"/dailyTasksInfo";
export const takeTaskPrizeUrl = httpUrl+"/getDailyPrize";
export const prizeRotaryUrl = httpUrl+"/prizeRotary";
export const day7InfoUrl = httpUrl+"/activityLogin7Info";
export const day7PrizeUrl = httpUrl+"/getActivityLogin7Prize";
export const shopListUrl = httpUrl+"/shopInfo";
export const getAdGuideUrl = httpUrl+"/getAdGuide";
export const finishAdUrl = httpUrl+"/finishAd";
export const goFightingUrl = httpUrl+"/goFighting";
export const battleResultUrl = httpUrl+"/battleResult";
export const addMultUrl = httpUrl+"/addMult";
export const goldListUrl = httpUrl+"/gunPDGList";
export const diamAdUrl = httpUrl+"/payDiamondFinishAd";
export const listMailUrl = httpUrl+"/listMail";
export const readMailUrl = httpUrl+"/readMail";
export const getMailPrizeUrl = httpUrl+"/getMailPrize";
export const freeCoinUrl = httpUrl+"/refreshFreeCoin";
export const worldRankUrl = httpUrl+"/getRankings";
export const updateWxInfoUrl = httpUrl+"/updatePlayerInfo";
export const exchangeTRMBUrl = httpUrl+"/exchangeTRMB";
export const useChipsUrl = httpUrl+"/useGunChips";
export const takeChipPrizeUrl = httpUrl+"/getGunRMB";
export const chipListUrl = httpUrl+"/gunOtherGunList";
export const getQrCodetUrl = httpUrl+"/getQCCode";
export const tixianUrl = httpUrl+"/transfers";
export const qrCodeImgHttp = httpUrl+"/qccode/";
export const rmbHistoryHttp = httpUrl+"/rmbHistory";
export const pmdUrl = httpUrl+"/getPMD";
export const bindWxUrl = httpUrl+"/bindWXAccount";

export const groupIndexUrl = httpUrl+"/groupIndex";     //战队首页协议
export const groupRatoryUrl = httpUrl+"/groupRotary";     //战队转盘协议
export const groupPrizeUrl = httpUrl+"/groupPrize";     //战队转盘次数必送协议
export const groupGetGXUrl = httpUrl+"/getContribute";     //领取贡献协议
export const groupFriendsListUrl = httpUrl+"/listFriends";     //小队长/队员 列表协议
export const groupGXListUrl = httpUrl+"/listContribute";     //贡献列表协议

export const tipMaxCount = 5;
export const popDuration = 5;

export const dailyRotType = 100; 

export const trmbAdCode = 100;                                  // 看视频获得获得现金券(战斗中)
export const reliveAdCode = 200;                                // 看视频复活
export const clearAdCode = 300;                                 // 观看广告消除障碍(战斗中)
export const dailyAdCode = 400;                                 // 观看广告领取7日奖励


export const prizeCoin = 0;                                     // 固定金币
export const prizePopRate = 1;                                  // 多少时间收益
export const prizeDiamond = 2;                                  // 钻石
export const prizeGun = 30;                                     // 枪械(固定枪械ID)
export const prizeUnlock = 31;                                  // random(当前解锁等级-偏移量)
export const prizeChip1 = 32;                                   // 平底锅碎片
export const prizeChip2 = 33;                                   // 镰刀碎片
export const prizeChip3 = 34;                                   // 撬棍碎片
export const prizeChip4 = 35;                                   // 砍刀碎片
export const prizeTicket = 40;                                  // 每日转盘券
export const prizeMul = 50;                                     // 翻倍
export const prizeLvUp = 60;                                    // 跃级
export const prizeRb = 70;                                      // 红包类型
export const prizeTRMB = 80;                                    // 元宝类型

export const levelTask = 22;                                    // 角色等级成就类型
export const maxChip = 100;                                     // 可合成的碎片

export const adCoolDur = 10;
export const appName = '射击训练大师';
// export const rewardVideo1 = '1bf2b0a5982ac2a9f2460823519fee96';
// export const bannerAd1 = '748c441e3df305d79351c169a56e7067';
export const rewardAdIds = ['adunit-9cc83e49024ebf7a', 'adunit-80dca578d99df515', 'adunit-2b965579d94560c4', 'adunit-bc154a21615f19bb'];
export const bannerAdIds = ['adunit-22e45b8d2fbdf0b0', 'adunit-f27465ea135346f1', 'adunit-a7b524a3669dce6e'];
// export const rewardVideo1 = 'adunit-9cc83e49024ebf7a';
// export const bannerAd1 = 'adunit-22e45b8d2fbdf0b0';

export const chipIcons = ['suipian_guo', 'suipian_lian', 'suipian_qiao', 'suipian_dao'];
export const goldItemIcons2 = ['wanzheng_guo', 'wanzheng_lian', 'wanzheng_qiao', 'wanzheng_dao'];
export const goldItemIcons3 = ['fenhongwuqi_1guo', 'fenhongwuqi_3liandao', 'fenhongwuqi_4qiaogun', 'fenhongwuqi_2kandao'];
export const goldItemIcons = ['hw1', 'hw4', 'hw44', 'hw2'];
export const goldItemNames = ['吉祥平底锅', '吉祥镰刀', '吉祥撬棍', '吉祥砍刀'];
export const goldNamesIm = ['fenhongwuqi_1guo_wenzi', 'fenhongwuqi_3liandao_wenzi', 'fenhongwuqi_4qiaogun_wenzi', 'fenhongwuqi_2kandao_wenzi'];
export const goldItemRewards = [200, 300, 310, 320];

export const groupLvNames = ['见习战队', '新晋战队', '先锋战队', '资深战队', '精锐战队', '传奇战队', '王牌战队', '战神战队'];

export const shareImgId1 = 'hNUXETM4Tc6Fg/qeS0Dkyg==' // 通过 MP 系统审核的图片编号
export const shareImgurl1 = 'https://mmocgame.qpic.cn/wechatgame/Ncl0ml1ibtEahK7bk5AXibYjc28Wk0GVcWNZCVeVYkE7TLDp5E255tVuTGveXyryvM/0' // 通过 MP 系统审核的图片地址
export const noticeUrl = 'https://yx.bigboluo.cn:8080/qccode/notice.json';

export const shareContents = [
    '我的战队成立啦，加入我的战队一起合成分红武器吧！战队抽奖100%获得现金红包哦！',
    '手气好不好，分红武器见分晓，分红武器人人必得，你能合出那一把？',
    '战队抽奖100%获得现金红包，如此赚钱良机岂容有失，还不赶紧行动？',
    '吃鸡6不6，关键是反应快不快，这款练枪小游戏训练你的核心反应能力，快来试试吧！',
    '先来的已经领到现金红包了，你还等什么？'
];
export const shareImgIds = [
    'CVL6NCjpSRCdKFlt1iWG/Q==',
    'q8Z+4rUgR0edKFu8Bt/keA==',
    'h5ECItSHQFy9xT98gWTtKw==',
    'yVmh39O/TJu8wo29Twv/mQ==',
    'IurgSie+R+yoOVAU0UvEZw=='
];

export const shareImgUrls = [
    'https://mmocgame.qpic.cn/wechatgame/7a1SKqYUULwt4oLSGzQG508zyLM2vEzna436s76YyYL1IBWbOtY7vTEhrp7aKktP/0',
    'https://mmocgame.qpic.cn/wechatgame/7a1SKqYUULz4e5VJ2icjAq3QUDuVCDOFs1uPGad6wqsibhVibFjYFkmtYElN1iammLua/0',
    'https://mmocgame.qpic.cn/wechatgame/7a1SKqYUULxE2XloJ3EohDGMMlWN07y3JwZ659PaXrgzLXubKKtHAQ3EE7SPyhu8/0',
    'https://mmocgame.qpic.cn/wechatgame/7a1SKqYUULwrp6iaD6HoO1WEG8EuskViblvwh3M5t1foQUH2kdQUMZd56mb502SY3N/0',
    'https://mmocgame.qpic.cn/wechatgame/7a1SKqYUULxWHARBkxrN9giajxtib5rNgu58zib3UonFGWsu5AO6PkpIcicT04GzIASN/0'
];

export function random(lower: number, upper: number) {
    return Math.floor(Math.random() * (upper - lower+1)) + lower;
}

export function formatTime(value: number) {
    value = Math.floor(value);
    let hour = Math.floor(value / 3600);
    let minute = Math.floor(value % 3600 / 60);
    let second = value % 60;

    let h = hour < 10 ? ('0' + hour) : hour;
    let min = minute < 10 ? ('0' + minute) : minute;
    let sec = second < 10 ? ('0' + second) : second;
    if (hour <= 0) {
        return min + ":" + sec;
    }else{
        return h + ":" + min + ":" + sec;
    }
}

export function simpleNum(value:number) {
    let units = ['','K','M','G','B','T','P'];
    let leftNum = value;
    let count = 0;

    let kVal = 0;
    let lVal = leftNum;

    if (value > 9999) {
        while(leftNum > 999){
            kVal = Math.floor(leftNum/1000);
            lVal = leftNum%1000;
            leftNum /= 1000;
            count++;
            
            if (count >= units.length-1) {
                break;
            }
        }
    }

    if (count == 0) {
        return String(Math.floor(leftNum));
    }
    // cc.log("######"+kVal);
    // cc.log("======"+lVal);
    return Math.floor(leftNum*10)/10+units[count];
    // return kVal+"."+Math.floor(lVal/100)+units[count];
    // return leftNum.toFixed(1)+units[count];
}

export function deepCopyJson(source: Object): Object {
    const newObject = {};
    for (const key of Object.keys(source)) {
        newObject[key] = typeof source[key] === 'object' ? deepCopyJson(source[key]) : source[key];
    }
    return newObject;
}

export function readStorage(keyWord: string) {

    let itemContent: any;

    if (cc.sys.WECHAT_GAME == cc.sys.platform || cc.sys.WECHAT_GAME_SUB == cc.sys.platform) {
        itemContent = window['wx'].getStorageSync(keyWord);
    } else {
        itemContent = cc.sys.localStorage.getItem(keyWord);
    }

    return itemContent;
}

export function saveStorage(key: string, value: any) {
    if (cc.sys.WECHAT_GAME == cc.sys.platform || cc.sys.WECHAT_GAME_SUB == cc.sys.platform) {
        window['wx'].setStorageSync(key, value);
    } else {
        cc.sys.localStorage.setItem(key, value);
    }
}

export function commonPost(url: string, eventName: string, params: object) {
    // let XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

    let xhr = new XMLHttpRequest();
    let data: any;
    let crypt = new xxtea();

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
            // console.log(xhr.responseText);
            var response = crypt.decryptFromBase64(xhr.responseText, cryptKey);
            console.info(response);
            
            NotificationCenter.Instance.emit(eventName, response);
        } else {
            // console.log("fail");
        }
    };
    xhr.open("POST", url, true);
    // xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');

    console.info("request:"+url);
    console.info("send：",params);
    data = "data="+crypt.encryptToBase64(JSON.stringify(params), cryptKey);
    xhr.send(data);
}

export function commonGet(url:string, eventName: string) {
    let xhr = new XMLHttpRequest();
    let data: any;
    // let crypt = new xxtea();

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
            // console.log(xhr.responseText);
            // var response = crypt.decryptFromBase64(xhr.responseText, cryptKey);
            var response = xhr.responseText;
            console.info(response);
            
            NotificationCenter.Instance.emit(eventName, response);
        } else {
            // console.log("fail");
        }
    };
    xhr.open("POST", url, true);
    // xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');

    console.info("request:"+url);
    // console.info("send：",params);
    // data = "data="+crypt.encryptToBase64(JSON.stringify(params), cryptKey);
    // xhr.send(data);
    // xhr.open()
}

export function loadImage(url: string, callback: Function){
    if (cc.sys.isNative) {
        if (url == null || url == "" || url.length < 11) {
            return;
        }
        if (window.jsb == null) {
            return;
        }

        let dirpath = jsb.fileUtils.getWritablePath() + 'customRes/';
        let md5URL = md5.b64_md5(url);
        let filepath = dirpath + md5URL + '.jpg';
        console.log("filepath ->",filepath);


        let loadEnd = ()=>{
            cc.assetManager.loadRemote(filepath, function(err: Error, tex:cc.Texture2D){
                if( err ){
                    console.log(err);
                    return;
                }else{
                    let spriteFrame = new cc.SpriteFrame(tex, new cc.Rect(0, 0, tex.width, tex.height));
                    callback(spriteFrame);
                }
            });
        }

        if( jsb.fileUtils.isFileExist(filepath) ){
            cc.log('local is find' + filepath);
            loadEnd();
            return;
        }

        let saveFile = (data)=>{
            if( typeof data !== 'undefined' ){
                if( !jsb.fileUtils.isDirectoryExist(dirpath) ){
                    jsb.fileUtils.createDirectory(dirpath);
                }else{
                    console.log("路径exist");
                }

                // new Uint8Array(data) writeDataToFile  writeStringToFile
                if( jsb.fileUtils.writeDataToFile( new Uint8Array(data) , filepath) ){
                    cc.log('Remote write file succeed.');
                    loadEnd();
                }else{
                    cc.log('Remote write file failed.');
                }
            }else{
                cc.log('Remote download file failed.');
            }
        };

        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            cc.log("xhr.readyState  " +xhr.readyState);
            cc.log("xhr.status  " +xhr.status);
            if (xhr.readyState === 4 ) {
                if(xhr.status === 200){
                    //responseType一定要在外面设置
                    // xhr.responseType = 'arraybuffer'; 
                    saveFile(xhr.response);
                }else{
                    saveFile(null);
                }
            }
        }.bind(this);
        //responseType一定要在外面设置
        xhr.responseType = 'arraybuffer';
        xhr.open("GET", url, true);
        xhr.send();

    }else{
        cc.assetManager.loadRemote(url, (err:Error,tex: cc.Texture2D) => {
            if (err) {
                console.log(err);
                return;
            }
            let spriteFrame = new cc.SpriteFrame(tex, new cc.Rect(0, 0, tex.width, tex.height));
            callback(spriteFrame);
        });

    }
}

var shareStartTimeSecond: number = 0;
/**
* 此方法每次点击分享就执行一次
* @param _callback处理分享的回调
*/
export function onShareGame (_callback: any) {
    console.log("---游戏回到前台---------------");
    // 记录点击分享的时间（秒级）
    ;
    shareStartTimeSecond = Date.now();
    let func = (_res: any)=>{
        let isShareSuccess: boolean = false;
        if (shareStartTimeSecond <= 0) {
            // 不处理
        }else {
            // 判断转发成功与否，按时间处理
            let interval: number = Date.now() - shareStartTimeSecond;
            shareStartTimeSecond = -1;
            // 我这里间隔设置为2.5s
            if (interval >= 2.5) {
                isShareSuccess = true;
                // wx.getShareInfo({
                //     shareTicket: _res.shareTicket,
                //     // timeout: 1,
                //     success:(res) => {
                //       console.log('============')
                //       console.log(res)
                //     },
                //     complete:(res) => {
                //       console.log(res)
                //       console.log('xxxxxxxxx')
                //     }
                //   });
            }
        }

        _callback(isShareSuccess);
        // 取消监听小游戏回到前台的事件
        window['wx'].offShow(func);
    };
    // 监听小游戏回到前台的事件
    window['wx'].onShow(func);
}

// 判断该用广告还是分享，还是没有用的
// 0：广告， 1： 分享， -1：没有用的
export function getADType(adCode: number){
    let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
    let userInfo = logicCenter.getUserInfo();
    let adPerConfigs = logicCenter.getAdPerConfigs();
    let adPerConfig = adPerConfigs.find((obj: any)=>{
        return obj.code == adCode;
    });

    let adPer = 100;
    if (adPerConfig != null && adPerConfig != undefined) {
        adPer = adPerConfig.pt;
    }

    console.log("adNum: "+userInfo.adNum+"/shareNum: "+userInfo.sharedNum+"/adPer:"+adPer);

    if (userInfo.adNum <= 0) {
        if (userInfo.sharedNum <= 0) {
            return -1;
        }
        return 1;
    } else {
        if (userInfo.sharedNum > 0) {
            let temp = random(1, 100);
            return temp>adPer?1:0;
        } else {
            return 0;
        }
    }
    return 1;
}

export function wxOpenShare() {
    if (cc.sys.WECHAT_GAME != cc.sys.platform) {
        return; 
    }

    let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
    let userInfo = logicCenter.getUserInfo();
    let contentIdx = random(0,4);
    // let codeStr = JSON.stringify({'myPromoterCode': userInfo.myPromoterCode});
    // console.log('query:'+codeStr)

    window['wx'].showShareMenu({
        withShareTicket: true,
        menus:['shareAppMessage', 'shareTimeline'],
        success: (res) => {
            window['wx'].onShareAppMessage(() => {
                return {
                        title: shareContents[contentIdx],
                        imageUrl: shareImgUrls[contentIdx],
                        imageUrlId: shareImgIds[contentIdx],
                        query: 'myPromoterCode='+userInfo.myPromoterCode
                    }
            });
        },
    });

    // 绑定分享参数
    window['wx'].onShareTimeline(() => {
        return {
            title: shareContents[contentIdx],
            imageUrl: shareImgUrls[contentIdx],
            imageUrlId: shareImgIds[contentIdx],
            query: 'myPromoterCode='+userInfo.myPromoterCode
        }
    })
    
    onShareGame(()=>{
        console.log('分享成功！');
        let popData = <TIP_INFO>{};
        popData.dur = 0.6;
        popData.type = 2;
        popData.tip = '分享成功！';
        NotificationCenter.Instance.emit('pop_tips', popData);
    });
}

export function wxShareWithFixPic(adCode: number, adData: number = 0) {

    if (cc.sys.WECHAT_GAME != cc.sys.platform) {
        NotificationCenter.Instance.emit("requestAdGuide", adCode, adData, 1);
        return; 
    }
    let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
    let userInfo = logicCenter.getUserInfo();
    let contentIdx = random(0,4);
    // let codeStr = JSON.stringify({'myPromoterCode': userInfo.myPromoterCode});
    // console.log('query:'+codeStr)
    window['wx'].shareAppMessage({
        title: shareContents[contentIdx],
        imageUrl: shareImgUrls[contentIdx],
        imageUrlId: shareImgIds[contentIdx],
        query: 'myPromoterCode='+userInfo.myPromoterCode
    });

    onShareGame(()=>{
        console.log('分享成功！');
        let popData = <TIP_INFO>{};
        popData.dur = 0.6;
        popData.type = 2;
        popData.tip = '分享成功！';
        NotificationCenter.Instance.emit('pop_tips', popData);
        if (adCode > 0) {
            NotificationCenter.Instance.emit("requestAdGuide", adCode, adData, 1);
        }
    });
}

export function wxShareWithCanvas(canvas, content: string, adCode: number = 0, adData: number = 0) {
    if (cc.sys.WECHAT_GAME != cc.sys.platform) {
        NotificationCenter.Instance.emit("requestAdGuide", adCode, adData, 1);
        return; 
    }
    window['wx'].updateShareMenu({
        withShareTicket: true
    });
    canvas.toTempFilePath({
        // x: 0,
        // y: 0,
        // width: canvas.width,
        // height:canvas.height,
        // destWidth: 500,
        // destHeight: 400,
        // fileType: "jpg",
        // quality: 1.0,
        success: (res) => {
            console.log(JSON.stringify(res));
            let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
            let userInfo = logicCenter.getUserInfo();
            // let codeStr = JSON.stringify({'myPromoterCode': userInfo.myPromoterCode});
            // console.log('query:'+codeStr)
            window['wx'].shareAppMessage({
                title: content,
                imageUrl: res.tempFilePath,
                query: 'myPromoterCode='+userInfo.myPromoterCode
            });
    
            onShareGame(()=>{
                console.log('分享成功！');
                let popData = <TIP_INFO>{};
                popData.dur = 0.6;
                popData.type = 2;
                popData.tip = '分享成功！';
                NotificationCenter.Instance.emit('pop_tips', popData);
                if (adCode > 0) {
                    NotificationCenter.Instance.emit("requestAdGuide", adCode, adData, 1);
                }
            });

        }
    });
}

export function wxSave2Album(canvas) {
    canvas.toTempFilePath({
        // x: 0,
        // y: 0,
        // width: canvas.width,
        // height:canvas.height,
        // destWidth: 500,
        // destHeight: 400,
        // fileType: "jpg",
        // quality: 1.0,
        success: (res) => {
            console.log(JSON.stringify(res));

            window['wx'].saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function () {
                    window['wx'].showToast({
                        title: '保存成功',
                        icon: 'success'
                    });
                },
                fail: function (e) {
                    window['wx'].showToast({
                        title: '保存失败',
                        icon: 'none'
                    });
                }
            });

        }
    });
}

export function cameraTakeShot(camera:cc.Camera, zoneWidth:number, zoneHeight: number) {
    // 设置你想要的截图内容的 cullingMask
    camera.cullingMask = 0xffffffff;

    // 新建一个 RenderTexture，并且设置 camera 的 targetTexture 为新建的 RenderTexture，这样 camera 的内容将会渲染到新建的 RenderTexture 中。
    let texture = new cc.RenderTexture();
    // let gl = cc.game._renderContext;
    // 如果截图内容中不包含 Mask 组件，可以不用传递第三个参数
    // texture.initWithSize(cc.visibleRect.width, cc.visibleRect.height, gl.STENCIL_INDEX8);
    texture.initWithSize(zoneWidth, zoneHeight, cc.RenderTexture.DepthStencilFormat.RB_FMT_D24S8);
    camera.targetTexture = texture;

    // 渲染一次摄像机，即更新一次内容到 RenderTexture 中
    camera.render();

    // 这样我们就能从 RenderTexture 中获取到数据了
    let data = texture.readPixels();

    // 接下来就可以对这些数据进行操作了
    let canvas = document.createElement('canvas'); 
    // let canvas = wx.createCanvas();
    let ctx = canvas.getContext("2d",{});
    let width = canvas.width = texture.width;
    let height = canvas.height = texture.height;

    canvas.width = texture.width;
    canvas.height = texture.height;

    // let image = wx.createImage();

    let rowBytes = width * 4;
    for (let row = 0; row < height; row++) {
        let srow = height - 1 - row;
        let imageData = ctx.createImageData(width, 1);
        let start = srow*width*4;
        for (let i = 0; i < rowBytes; i++) {
            imageData.data[i] = data[start+i];
        }

        ctx.putImageData(imageData, 0, row);
    }

    return canvas;
}